<?php
/*  vim: set expandtab shiftwidth=4 softtabstop=4 tabstop=4:    */

class Control {
    private static $config;
    private static $control;
    private static $db;

    public function __construct($config='') {
        if(isset($config['usessl']) && $config['usessl'] === TRUE) {
            if(!isset($_SERVER['HTTPS'])) {
                header("Location : ". $config['baseUrl']);
            }
        }
        
        //loads DB
        if(isset($config['usedb']) && $config['usedb'] === TRUE && !is_array(self::$db)) {
        	if(isset($config['db'][0]) && count($config['db']) > 1) {
        		foreach($config['db'] as $key => $dbconf) {
        			if($key == 0 && isset($dbconf['master']) && $dbconf['master'] == TRUE) {
        				self::$db['default']   =   new DBv2($config['db'][0]['core'],$config['db'][0]['dsn']);
        			} else {
	        			if(isset($dbconf['dsn']['master']) && $dbconf['dsn']['master'] == TRUE) {
	        				self::$db['default']->addMaster($config['db'][$key]['core'],$config['db'][$key]['dsn']);
	        			} else {
	        				self::$db['default']->addSlave($config['db'][$key]['core'],$config['db'][$key]['dsn']);
	        			}
        			}
        		}
        	} else {
        		self::$db['default']   =   new DBv2($config['db']['core'],$config['db']['dsn']);
        	}
            //for backward compatibility
            DB::$db = self::$db['default'];
        }
        
        //loads Auth
        if(isset($config['useauth']) && $config['useauth'] === TRUE) {
            if(isset($config['auth']['engine']) && !empty($config['auth']['engine'])) {
                self::$control->auth    =   new Auth($config['auth']['engine']);
            }
        }

        if(isset($_SERVER['HTTP_X_REQUESTED_WITH']) && $_SERVER['HTTP_X_REQUESTED_WITH'] == "XMLHttpRequest") {
            self::$control->isHttp  =   FALSE;
            self::$control->isAjax  =   TRUE;
            self::$control->viewType=	"ajax";
            self::$control->view	=   new Dom();
        } else {
            self::$control->isHttp  =   TRUE;
            self::$control->isAjax  =   FALSE;
            self::$control->viewType=	"http";
            self::$control->view	=   new Dom_Html();
        }

        if(isset($config) && is_array($config)) self::loadConfig($config);
    }

    /* loadConfig(array $config) : Loads config multi dimensional array into static property for use throughout
     *
     *  @access public
     *  @param array $config     - config array
     */
    public function loadConfig(array $config) {
        self::$config   =   $config;
    }
    

    /*  initialize()    :   Initialize the controller
     *
     *  @access public
     */
    public function initialize() {
        try {
            if(filter_input(INPUT_GET, "m")) {
                self::loadModule($_GET['m']);
            } elseif(isset(self::$config['defaultModule']) && !empty(self::$config['defaultModule'])) {
                self::loadModule(self::$config['defaultModule']);
            } else {
                throw new Exception("Not able to determine module.");
            }
        } catch (Exception $e) {
            die("Unable to initialize [". $e->getMessage() ."]");
        }
    }

    /*  loadModule(string $moduleName)  :   Load the desired module
     *
     *      @access private
     *      @param  string  $moduleName     -   The name of the module to load
     */
    private function loadModule($moduleName) {
        $moduleDir  =   module .$moduleName;

        if(is_dir($moduleDir) && is_readable($moduleDir) && file_exists($moduleDir. slash ."index.php")) {
            if(file_exists($moduleDir. slash ."config.php")) {
                require_once $moduleDir. slash ."config.php";
            }

            require_once $moduleDir. slash ."index.php";
        } else {
            throw new Exception("Unable to initialize module (".$moduleName.")");
        }
    }

    /*
     *  getControl()                    :   Get the control variable instead of having it globalized
     *
     *      @access public
     *      @return         $control        -   The controller variable
     */
    public function getControl() {
        return self::$control->view;
    }

    public function getView() {
    	return self::$control->view;
    }
    
    /*
     *  getConfig()                     :   Get the global configurations
     *
     *      @access public
     *      @return         $config         -   Returns the configuration array
     */
    public function getConfigs() {
        return self::$config;
    }
    
    /*
     * 	addDb($core,array $dsn)
     * 
     * 	@access public
     *  @param string $core
     *  @param array $dsn
     *  @return void
	 */
    public function addDb($core, array $dsn, $name = NULL) {
    	if(isset($name) && !empty($name)) { //custom name
    		self::$db[$name] = new DBv2($core,$dsn);
    	} else {
    		self::$db[$dsn['name']] = new DBv2($core,$dsn);
    	}
    }
    
    /*
     * 	getDb()	: Get the DB instance you wish to work with
     * 
     * 	@access public
     * 	@param	mixed $instance (numeric/associative)
     * 	@return $DB instance.
	 */
    public function getDb($instance = 'default') {
    	return self::$db[$instance];
    }
    
    public function getViewType() {
    	
    }
    
    /*
     * Destructor
	 */
    public function __destruct() {
        self::initialize();
    }
}
?>
